<template>
  <div class="my-qrcode-page">
    <!-- 顶部导航 -->
    <van-nav-bar 
      title="我的收款码" 
      left-arrow 
      @click-left="goBack"
    />
    
    <!-- 主要内容 -->
    <div class="content">
      <!-- 收款码信息卡片 -->
      <div class="qrcode-card">
        <div class="card-header">
          <van-icon name="qr" color="#157658" size="24" />
          <span class="card-title">收款码信息</span>
        </div>
        
        <!-- 收款商户名 -->
        <div class="form-item">
          <label class="form-label">收款商户名</label>
          <div class="form-input">
            <van-field
              v-model="merchantName"
              placeholder="请输入收款商户名"
              :disabled="auditStatus === 'pending'"
              @blur="onMerchantNameChange"
            />
          </div>
        </div>
        
        <!-- 收款码图片 -->
        <div class="form-item">
          <label class="form-label">收款码</label>
          <div class="qrcode-upload">
            <!-- 已上传的收款码 -->
            <div v-if="qrcodeUrl" class="qrcode-preview">
              <img 
                :src="qrcodeUrl" 
                class="qrcode-image" 
                @click="previewQrcode"
                alt="收款码"
              />
              <div class="qrcode-actions">
                <van-button 
                  type="primary" 
                  size="small"
                  @click="editQrcode"
                  :disabled="auditStatus === 'pending'"
                >
                  重新上传
                </van-button>
                <van-button 
                  type="default" 
                  size="small"
                  @click="previewQrcode"
                >
                  预览
                </van-button>
              </div>
            </div>
            
            <!-- 未上传时显示上传按钮 -->
            <div v-else class="upload-area" @click="chooseQrcode">
              <van-icon name="plus" size="32" color="#999" />
              <span class="upload-text">上传收款码</span>
            </div>
          </div>
        </div>
        
        <!-- 审核状态 -->
        <div v-if="auditStatus" class="audit-status">
          <div class="status-item">
            <span class="status-label">审核状态：</span>
            <span class="status-value" :class="auditStatus">
              {{ getAuditStatusText(auditStatus) }}
            </span>
          </div>
          
          <!-- 审核时间 -->
          <div v-if="auditTime" class="status-item">
            <span class="status-label">审核时间：</span>
            <span class="status-time">{{ auditTime }}</span>
          </div>
          
          <!-- 审核人 -->
          <div v-if="auditorName" class="status-item">
            <span class="status-label">审核人：</span>
            <span class="status-auditor">{{ auditorName }}</span>
          </div>
          
          <!-- 审核备注 -->
          <div v-if="auditRemark" class="status-item">
            <span class="status-label">审核备注：</span>
            <span class="status-remark">{{ auditRemark }}</span>
          </div>
          
          <!-- 提交时间 -->
          <div v-if="submitTime" class="status-item">
            <span class="status-label">提交时间：</span>
            <span class="status-time">{{ submitTime }}</span>
          </div>
        </div>
      </div>
      
              <!-- 操作按钮 -->
        <div class="action-buttons">
          <!-- 调试按钮 -->
          <van-button 
            type="default" 
            size="small" 
            @click="debugData"
            style="margin-bottom: 10px; margin-right: 10px;"
          >
            调试数据
          </van-button>
          
          <!-- 刷新审核信息按钮 -->
          <van-button 
            type="default" 
            size="small" 
            @click="refreshAuditInfo"
            style="margin-bottom: 10px;"
          >
            刷新审核信息
          </van-button>
          
          <van-button 
            v-if="!qrcodeUrl || !merchantName"
            type="primary" 
            size="large" 
            block
            @click="submitForReview"
            :disabled="!canSubmit"
          >
            提交审核
          </van-button>
          
          <van-button 
            v-else-if="auditStatus === 'rejected'"
            type="primary" 
            size="large" 
            block
            @click="resubmitForReview"
          >
            重新提交
          </van-button>
          
          <van-button 
            v-else-if="auditStatus === 'approved'"
            type="success" 
            size="large" 
            block
            disabled
          >
            审核已通过
          </van-button>
          
          <van-button 
            v-else-if="auditStatus === 'pending'"
            type="info" 
            size="large" 
            block
            disabled
          >
            审核中...
          </van-button>
          
          <van-button 
            v-else
            type="primary" 
            size="large" 
            block
            @click="submitForReview"
          >
            提交审核
          </van-button>
        </div>
      
      <!-- 使用说明 -->
      <div class="instructions">
        <div class="instructions-title">
          <van-icon name="info-o" color="#1989fa" />
          <span>使用说明</span>
        </div>
        <div class="instructions-content">
          <p>1. 请填写真实的收款商户名</p>
          <p>2. 上传清晰的收款码图片（支持微信、支付宝等）</p>
          <p>3. 点击"提交审核"按钮，系统会创建审核记录</p>
          <p>4. 提交后信息将进入审核状态，无法修改</p>
          <p>5. 客服将在1-3个工作日内完成审核</p>
          <p>6. 审核通过后，系统会自动更新您的收款码信息</p>
          <p>7. 审核期间请耐心等待，请仔细核对后再提交</p>
          <p>8. 审核结果会显示详细的状态信息和备注说明</p>
        </div>
      </div>
    </div>
    
    <!-- 文件选择器 -->
    <input
      ref="fileInput"
      type="file"
      accept="image/*"
      style="display: none"
      @change="onFileChange"
    />
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { showToast, showConfirmDialog } from 'vant'
import { getUserQrcode, updateUserQrcode, submitUserAudit, getUserAuditInfo } from '@/api/user'

const router = useRouter()

// 响应式数据
const merchantName = ref('')
const qrcodeUrl = ref('')
const auditStatus = ref('') // pending, approved, rejected
const auditRemark = ref('')
const auditTime = ref('') // 审核时间
const auditorName = ref('') // 审核人姓名
const submitTime = ref('') // 提交时间
const fileInput = ref(null)

// 计算属性
const canSubmit = computed(() => {
  return merchantName.value.trim() && qrcodeUrl.value
})

// 页面加载时获取数据
onMounted(async () => {
  await loadUserQrcode()
  await loadAuditInfo()
})

// 加载用户收款码信息
const loadUserQrcode = async () => {
  try {
    const response = await getUserQrcode()
    console.log('收款码信息响应:', response)
    
    if (response.success !== false) {
      const data = response.data || response
      console.log('解析的收款码数据:', data)
      console.log('real_name字段值:', data.real_name)
      console.log('merchant_name字段值:', data.merchant_name)
      console.log('bank_qrcode_url字段值:', data.bank_qrcode_url)
      
      merchantName.value = data.merchant_name || data.real_name || ''
      qrcodeUrl.value = data.bank_qrcode_url || ''
      
      console.log('设置后的商户名:', merchantName.value)
      console.log('设置后的收款码URL:', qrcodeUrl.value)
    }
  } catch (error) {
    console.error('加载收款码信息失败:', error)
    showToast('加载失败')
  }
}

// 加载审核信息
const loadAuditInfo = async () => {
  try {
    const response = await getUserAuditInfo()
    console.log('审核信息响应:', response)
    
    if (response.success) {
      const data = response.data || {}
      console.log('审核数据详情:', data)
      
      auditStatus.value = data.status || ''
      auditRemark.value = data.auditRemark || data.audit_remark || data.remark || ''
      auditTime.value = data.auditTime || data.audit_time || ''
      auditorName.value = data.auditorName || data.auditor_name || ''
      submitTime.value = data.createTime || data.create_time || ''
      
      console.log('解析后的审核信息:')
      console.log('- 状态:', auditStatus.value)
      console.log('- 备注:', auditRemark.value)
      console.log('- 审核时间:', auditTime.value)
      console.log('- 审核人:', auditorName.value)
      console.log('- 提交时间:', submitTime.value)
    }
  } catch (error) {
    console.error('加载审核信息失败:', error)
    // 审核信息加载失败不影响主要功能
  }
}

// 选择收款码图片
const chooseQrcode = () => {
  if (auditStatus.value === 'pending') {
    showToast('审核中，无法修改')
    return
  }
  
  fileInput.value?.click()
}

// 文件选择变化
const onFileChange = async (event) => {
  const file = event.target.files[0]
  if (!file) return
  
  // 验证文件类型
  if (!file.type.startsWith('image/')) {
    showToast('请选择图片文件')
    return
  }
  
  // 验证文件大小（限制为5MB）
  if (file.size > 5 * 1024 * 1024) {
    showToast('图片大小不能超过5MB')
    return
  }
  
  try {
    await uploadQrcode(file)
  } catch (error) {
    console.error('上传收款码失败:', error)
    showToast('上传失败')
  }
  
  // 清空文件选择器
  event.target.value = ''
}

// 上传收款码
const uploadQrcode = async (file) => {
  try {
    showToast('上传中...')
    
    const formData = new FormData()
    formData.append('file', file)
    
    const response = await fetch('/v1/file/upload/qrcode', {
      method: 'POST',
      headers: {
        'Authorization': `Bearer ${localStorage.getItem('token') || ''}`
      },
      body: formData
    })
    
    const result = await response.json()
    
    if (result.success) {
      qrcodeUrl.value = result.url
      showToast('上传成功')
      
      // 上传成功后不自动保存，等用户提交审核
    } else {
      throw new Error(result.message || '上传失败')
    }
  } catch (error) {
    console.error('上传收款码失败:', error)
    showToast(error.message || '上传失败')
  }
}

// 编辑收款码
const editQrcode = () => {
  chooseQrcode()
}

// 预览收款码
const previewQrcode = () => {
  if (!qrcodeUrl.value) return
  
  // 使用Vant的图片预览
  const images = [qrcodeUrl.value]
  // 这里可以使用Vant的图片预览组件
  // 或者直接在新窗口打开
  window.open(qrcodeUrl.value, '_blank')
}

// 商户名变化
const onMerchantNameChange = async () => {
  // 商户名变化时不自动保存，等用户主动提交审核
}

// 保存收款码信息（临时保存，不提交审核）
const saveQrcodeInfo = async () => {
  try {
    const data = {
      real_name: merchantName.value.trim(),
      bank_qrcode_url: qrcodeUrl.value
    }
    
    // 这里只是临时保存到本地状态，不调用后端API
    // 真正的保存是在提交审核时进行的
    showToast('信息已保存，请提交审核')
  } catch (error) {
    console.error('保存收款码信息失败:', error)
    showToast('保存失败')
  }
}

// 提交审核
const submitForReview = async () => {
  if (!canSubmit.value) {
    showToast('请完善收款码信息')
    return
  }
  
  try {
    await showConfirmDialog({
      title: '提交审核',
      message: '确认提交收款码信息进行审核？提交后将无法修改。'
    })
    
    // 准备审核数据（使用下划线格式，后端会自动转换为驼峰格式）
    const auditData = {
      merchant_name: merchantName.value.trim(),
      bank_qrcode_url: qrcodeUrl.value
    }
    
    // 添加调试日志
    console.log('准备提交的审核数据:', auditData)
    console.log('商户名:', merchantName.value)
    console.log('收款码URL:', qrcodeUrl.value)
    
    // 验证数据
    if (!auditData.real_name || !auditData.bank_qrcode_url) {
      showToast('请完善收款码信息')
      return
    }
    
    await submitUserAudit(auditData)
    showToast('提交成功，等待审核')
    
    // 刷新审核信息
    await loadAuditInfo()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('提交审核失败:', error)
      showToast('提交失败')
    }
  }
}

// 重新提交审核
const resubmitForReview = async () => {
  await submitForReview()
}

// 调试数据
const debugData = async () => {
  console.log('=== 调试信息 ===')
  console.log('商户名:', merchantName.value)
  console.log('商户名类型:', typeof merchantName.value)
  console.log('商户名长度:', merchantName.value?.length)
  console.log('收款码URL:', qrcodeUrl.value)
  console.log('收款码URL类型:', typeof qrcodeUrl.value)
  console.log('收款码URL长度:', qrcodeUrl.value?.length)
  console.log('canSubmit:', canSubmit.value)
  console.log('审核状态:', auditStatus.value)
  console.log('审核备注:', auditRemark.value)
  console.log('审核时间:', auditTime.value)
  console.log('审核人:', auditorName.value)
  console.log('提交时间:', submitTime.value)
  
  // 准备发送的数据格式
  const auditData = {
    merchant_name: merchantName.value.trim(),
    bank_qrcode_url: qrcodeUrl.value
  }
  console.log('准备发送的审核数据:', auditData)
  
  // 实时获取审核信息
  try {
    console.log('=== 实时获取审核信息 ===')
    const response = await getUserAuditInfo()
    console.log('原始API响应:', response)
    
    if (response.success) {
      const data = response.data || {}
      console.log('API返回的数据:', data)
      console.log('所有字段:', Object.keys(data))
      console.log('字段值详情:')
      Object.keys(data).forEach(key => {
        console.log(`- ${key}:`, data[key])
      })
    }
  } catch (error) {
    console.error('获取审核信息失败:', error)
  }
  
  // 显示在页面上
  showToast(`商户名: ${merchantName.value || '空'}, 收款码: ${qrcodeUrl.value ? '已上传' : '未上传'}`)
}

// 刷新审核信息
const refreshAuditInfo = async () => {
  try {
    showToast('刷新中...')
    await loadAuditInfo()
    showToast('刷新成功')
  } catch (error) {
    console.error('刷新审核信息失败:', error)
    showToast('刷新失败')
  }
}

// 获取审核状态文本
const getAuditStatusText = (status) => {
  const statusMap = {
    'pending': '审核中',
    'approved': '已通过',
    'rejected': '已拒绝'
  }
  return statusMap[status] || status
}

// 返回上一页
const goBack = () => {
  router.back()
}
</script>

<style lang="scss" scoped>
.my-qrcode-page {
  background-color: #f5f5f5;
  min-height: 100vh;
  padding-bottom: 20px;
}

.content {
  padding: 20px;
}

.qrcode-card {
  background: #fff;
  border-radius: 12px;
  padding: 20px;
  margin-bottom: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  
  .card-header {
    display: flex;
    align-items: center;
    margin-bottom: 20px;
    
    .card-title {
      margin-left: 10px;
      font-size: 18px;
      font-weight: bold;
      color: #333;
    }
  }
}

.form-item {
  margin-bottom: 20px;
  
  .form-label {
    display: block;
    font-size: 16px;
    font-weight: 500;
    color: #333;
    margin-bottom: 8px;
  }
  
  .form-input {
    :deep(.van-field) {
      background: #f8f9fa;
      border-radius: 8px;
      
      .van-field__control {
        font-size: 16px;
      }
    }
  }
}

.qrcode-upload {
  .qrcode-preview {
    text-align: center;
    
    .qrcode-image {
      width: 200px;
      height: 200px;
      object-fit: contain;
      border: 2px solid #e8e8e8;
      border-radius: 8px;
      margin-bottom: 15px;
      cursor: pointer;
      transition: border-color 0.3s;
      
      &:hover {
        border-color: #157658;
      }
    }
    
    .qrcode-actions {
      display: flex;
      gap: 10px;
      justify-content: center;
    }
  }
  
  .upload-area {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    width: 200px;
    height: 200px;
    border: 2px dashed #ddd;
    border-radius: 8px;
    cursor: pointer;
    transition: border-color 0.3s;
    
    &:hover {
      border-color: #157658;
      background: #f8f9fa;
    }
    
    .upload-text {
      margin-top: 10px;
      color: #999;
      font-size: 14px;
    }
  }
}

.audit-status {
  background: #f8f9fa;
  border-radius: 8px;
  padding: 15px;
  margin-top: 20px;
  
  .status-item {
    display: flex;
    margin-bottom: 8px;
    
    &:last-child {
      margin-bottom: 0;
    }
    
    .status-label {
      font-size: 14px;
      color: #666;
      min-width: 80px;
    }
    
    .status-value {
      font-size: 14px;
      font-weight: 500;
      
      &.pending {
        color: #ff9500;
      }
      
      &.approved {
        color: #07c160;
      }
      
      &.rejected {
        color: #ee0a24;
      }
    }
    
    .status-remark {
      font-size: 14px;
      color: #333;
      flex: 1;
    }
    
    .status-time {
      font-size: 14px;
      color: #666;
      flex: 1;
    }
    
    .status-auditor {
      font-size: 14px;
      color: #157658;
      font-weight: 500;
      flex: 1;
    }
  }
}

.action-buttons {
  margin-bottom: 20px;
}

.instructions {
  background: #fff;
  border-radius: 12px;
  padding: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  
  .instructions-title {
    display: flex;
    align-items: center;
    margin-bottom: 15px;
    
    span {
      margin-left: 8px;
      font-size: 16px;
      font-weight: bold;
      color: #333;
    }
  }
  
  .instructions-content {
    p {
      margin: 8px 0;
      font-size: 14px;
      color: #666;
      line-height: 1.5;
    }
  }
}
</style> 